const Koa = require('koa')
const app = new Koa()
const onerror = require('koa-onerror')
const KoaBody = require('koa-body')
const logger = require('koa-logger')

const routerInit = require('./routes/index').default

//解决跨域
app.use(async (ctx, next) => {
    ctx.set("Access-Control-Allow-Origin", "*");
    ctx.set(
        "Access-Control-Allow-Headers",
        "Content-Type, Content-Length,token,Authorization, Accept, X-Requested-With , yourHeaderFeild"
    );
    ctx.set("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS");
    if (ctx.method == "OPTIONS") {
        ctx.body = 200;
    } else {
        await next();
    }
});
app.use(KoaBody({
    multipart: true, // 支持文件上传
    formidable: {
        maxFileSize: 200 * 1024 * 1024 // 设置上传文件大小最大限制，默认2M
    }
}));
app.use(require('koa-static')(__dirname + '/public'))
// routes
routerInit(app)



// logger
// app.use(async (ctx, next) => {
//   const start = new Date()
//   await next()
//   const ms = new Date() - start
//   console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
// })



// error-handling
app.on('error', (err, ctx) => {
    console.error('server error', err, ctx)
});

module.exports = app
